package com.lixin.smartclassroom.ui.home.tab5.activity

import android.content.Context
import android.os.Environment
import android.util.Log
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.drake.brv.utils.bindingAdapter
import com.drake.net.Get
import com.drake.net.component.Progress
import com.drake.net.interfaces.ProgressListener
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.deletefolder
import com.lixin.smartclassroom.api.folderlist
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.common.addDatabaseDialog
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityDatabaseDetailBinding
import com.lixin.smartclassroom.databinding.ActivityDatabasePreviewBinding
import com.lixin.smartclassroom.ui.home.adapter.databaseDetail
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.commonDialog
import com.lixinkeji.extension.getIntentSerializable
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.load
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.removeAt
import com.lixinkeji.extension.start
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.SaveUtils
import java.io.File


/**
 * Description 资料库
 * Author: lwc
 * Date:2023/12/11 9:21
 */
class DatabaseDetailPreviewAct : BaseActivity<ActivityDatabasePreviewBinding>() {
    override fun getViewBinding() = ActivityDatabasePreviewBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    override fun title() = "资料库"
    private lateinit var dataListBean: DataListBean

    override fun iniView() {
        binding.apply {
            dataListBean = getIntentSerializable("dataListBean")
            if (dataListBean.url?.contains(".mp4") == true) {
                videoPlayer.visible()
                videoPlayer.setUp(dataListBean.url, true, "")
                //增加封面
                val imageView = ImageView(this@DatabaseDetailPreviewAct)
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                Glide.with(this@DatabaseDetailPreviewAct).load(dataListBean.url).into(imageView)
                videoPlayer.thumbImageView = imageView
                videoPlayer.backButton.gone()
                videoPlayer.fullscreenButton.visible()
                //不需要屏幕旋转
                videoPlayer.isNeedOrientationUtils = false
                img.gone()
            } else {
                img.visible()
                videoPlayer.gone()
                img.load(dataListBean.url!!)
            }
        }
    }


    override fun onClick() {

        binding.btnDownload.onClick {
            downloadData()
        }
        binding.btnDelete.onClick {

            commonDialog("删除文件夹",
                content = "删除后，所有数据将会清空\n且不可恢复，请谨慎操作",
                cancel = "取消",
                sure = "删除",
                onSure = {
                    deleteData()
                })


        }
    }

    private fun downloadData() {
        binding.apply {
            scopeNetLife {
                llProgress.visible()
                scopeNetLife {
                    val file =
                        Get<File>(dataListBean.url!!) {
                            setDownloadFileName(
                                "smartclass" + dataListBean.title!!
                            )
                            setDownloadDir(getFilesPath(this@DatabaseDetailPreviewAct)!!)
                            Log.e("-------------", "downloadData: " + filesDir.path)
                            setDownloadMd5Verify()
                            addDownloadListener(object : ProgressListener() {
                                override fun onProgress(p: Progress) {
                                    binding.seekBar?.post {
                                        val progress = p.progress()
                                        seekBar.progress = progress
                                        tvProgress.text =
                                            "下载进度: $progress% 下载速度: ${p.speedSize()}     " +
                                                    "\n\n文件大小: ${p.totalSize()}  已下载: ${p.currentSize()}  剩余大小: ${p.remainSize()}" +
                                                    "\n\n已使用时间: ${p.useTime()}  剩余时间: ${p.remainTime()}"
                                    }
                                }
                            })
                        }.await()
                    saveSuccessDialog("下载成功")
                    llProgress.gone()
                    if (file.path.endsWith(".mp4"))
                        SaveUtils.saveVideoToAlbum(this@DatabaseDetailPreviewAct, file.path)
                    else
                        SaveUtils.saveImgFileToAlbum(this@DatabaseDetailPreviewAct, file.path)
                }
            }
        }
    }

    private fun deleteData() {
        binding.apply {
            scopeNetLife {
                deletefolder(dataListBean.id!!)
                saveSuccessDialog("删除成功")
            }
        }
    }

    private fun getFilesPath(context: Context): String? {
        val filePath: String =
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
                //外部存储可用
                context.getExternalFilesDir(null)?.path!!
            } else {
                //外部存储不可用
                context.filesDir.path
            }
        return filePath
    }


}